package com.example.james.networktest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by James on 1/30/2018.
 */

public class HttpUtil {

    public static void sendHttpRequest(final String address, final HttpCallbackListener httpCallbackListener){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                StringBuilder stringBuilder = new StringBuilder();
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    while ((line = bufferedReader.readLine()) != null){
                        stringBuilder.append(line);
                    }
                } catch (Exception e){
                    e.printStackTrace();
                    if (httpCallbackListener != null){
                        httpCallbackListener.onError(e);
                    }
                } finally {
                    if (connection != null){
                        connection.disconnect();
                    }
                    if (httpCallbackListener != null){
                        httpCallbackListener.onFinish(stringBuilder.toString());
                    }
                }
            }
        }).start();
    }

    public static void sendOkHttpRequest(final String address, final Callback callback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(address).build();
                okHttpClient.newCall(request).enqueue(callback);
            }
        }).start();
    }
}
